<template>
  <div>
    <div class="searchform">
      <ToolBar :filters="filters" :getList="getList" :handleAdd="handleCreate"/>
    </div>
    <el-table v-loading="listLoading" :data="taskList" element-loading-text="Loading" fit highlight-current-row  :default-sort = "{prop: 'createdAt', order: 'descending'}">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-row>
            <el-col :span="24">
              <el-card class="box-card">
                <el-table :data="scope.row.projectList" stripe style="width: 100%" border :default-sort = "{prop: 'date', order: 'descending'}"> 
                  <el-table-column type="index" width="40"></el-table-column>
                  <el-table-column prop="name" label="子项目名称" min-width="100"></el-table-column>
                  <el-table-column prop="engineerId" label="工程师" min-width="100" align="center" >
                    <template slot-scope="scope">
                      <span v-if="scope.row.engineerId == 1">钱云龙</span>
                      <span v-if="scope.row.engineerId == 3">刘铮臻</span>
                      <span v-if="scope.row.engineerId == 4">周晓华</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="任务状态" prop="state" align="center" min-width="100" >
                    <template slot-scope="scope">
                      <el-tag v-if="scope.row.state=== 1" type="warning">进行中</el-tag>
                      <el-tag v-else-if="scope.row.state=== 2" type="warning">暂停</el-tag>
                      <el-tag v-else-if="scope.row.state=== 3" type="warning">中止</el-tag>
                      <el-tag v-else type="primary">已完成</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="计划时间" sortable>
                    <template slot-scope="scope">
                      <span>{{ scope.row.planStartDate | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="完成时间" sortable>
                    <template slot-scope="scope">
                      <span>{{ scope.row.planEndDate | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="checkPermission(['engineer'])" label="操作" min-width="150" >
                    <template slot-scope="scope">
                     <el-button type="primary" size="small" @click="handleProgress(scope.$index, scope.row)">进度</el-button> 
                     <el-button type="warning" size="small" @click="handleProjectTrack(scope.$index, scope.row)">项目跟踪</el-button> 
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" prop="id" width="95" type="index"></el-table-column>
      <el-table-column label="项目名称" prop="name"></el-table-column>
      <el-table-column label="创建时间" prop="createdAt" sortable align="center" min-width="100" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.createdAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" prop="state" align="center" min-width="100" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state=== 1" type="warning">进行中</el-tag>
          <el-tag v-else-if="scope.row.state=== 2" type="warning">暂停</el-tag>
          <el-tag v-else-if="scope.row.state=== 3" type="warning">中止</el-tag>
          <el-tag v-else type="primary">已完成</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="所属客户" prop="customerName" align="center"></el-table-column>
      <el-table-column label="操作" align="center" min-width="150">
        <template slot-scope="scope">
          <el-button size="small" type="primary" @click="handleClick(scope.$index, scope.row)">子项目</el-button>
          <el-button v-if="checkPermission(['manager'])" size="small" type="warning" @click="handleUpdate(scope.$index, scope.row)">
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button v-if="checkPermission(['manager'])" size="small" type="warning" @click="handleUpdatePic(scope.$index, scope.row)">编辑项目图片</el-button>
          <el-button type="warning" size="small" @click="handleTaskTrack(scope.$index, scope.row)">项目跟踪</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--翻页-->
    <Pagination v-show="total>10" :total="total" :pageSize="pagesize" :handleCurrentChange="handleCurrentChange"/>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form label-width="130px" :model="Form" :rules="FormRules" ref="dataForm">
        <el-form-item label="项目名称" prop="name" width="100%">
          <el-input v-model="Form.name"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" prop="planStartDate" width="100%">
          <el-date-picker v-model="Form.createdAt" type="datetime" placeholder="请选择时间"/>
        </el-form-item>
        <el-form-item label="服务客户" prop="customerId">
          <el-select v-model="Form.customerId" class="filter-item" placeholder="请选择所属客户">
            <el-option v-for="item in customersOptions" :key="item.customerId" :label="item.customerName" :value="item.customerId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="服务地点" prop="customerAddr" width="100%">
          <el-input v-model="Form.customerAddr"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="customerContact" width="100%">
          <el-input v-model="Form.customerContact"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item label="实施计划时间" prop="planStartDate" width="100%">
              <el-date-picker v-model="Form.planStartDate" type="datetime" placeholder="请选择时间" :picker-options="StartOptions"/>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="完成时限" prop="planEndDate" width="100%">
              <el-date-picker v-model="Form.planEndDate" type="datetime" placeholder="请选择时间" :picker-options="EndOptions"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="项目描述" width="100%">
          <el-input type="textarea" v-model="Form.description"></el-input>
        </el-form-item>
        <el-form-item label="项目图片" prop="picList" width="100%" v-if="dialogStatus==='create'">
          <UploadCreateImg ref="taskPic" :isMultiple="true" :FileUrl="FileUrl" :Data="Data" :picList="Form.picList" :handleChange="handleChange"></UploadCreateImg>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>

    <!-- 图片编辑弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogPicListVisible" :close-on-click-modal="false">
      <UploadImg
        :picList="picList"
        :FileUrl="FileUrl"
        :Data="Data"
        :handleAvatarSuccess="handleAvatarSuccess"
        :handleRemove="handleRemove"
        :beforeRemove="beforeRemove"
      ></UploadImg>
    </el-dialog>
  </div>
</template>
<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { getEngineerList } from "@/api/users";
import Pagination from "@/views/layout/components/Pagination";
import ToolBar from "@/views/layout/components/ToolBar";
import { getCustomerAll } from "@/api/customers";
import {
  getTaskList,
  createTask,
  updateTask,
  deleteTask,
  getTaskData,
  deletePic
} from "@/api/task";
import UploadCreateImg from "@/components/Upload/UploadImg3";
import UploadImg from "@/components/Upload/UploadImg2";
import { isvalidPhone } from "@/utils/validate";
const validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入电话号码"));
  } else if (!isvalidPhone(value)) {
    callback(new Error("请输入正确的11位手机号码"));
  } else {
    callback();
  }
};
export default {
  components: { ToolBar, UploadCreateImg, UploadImg, Pagination },
  props: {
    state: {
      type: String,
      default: "0"
    }
  },

  data() {
    return {
      taskList: [],
      customersOptions: [],
      listLoading: false,
      Data: {},
      picList: [],
      FileUrl: "http://gsp.coldcloud.com/task/pic/insert",
      filters: {
        name: "",
        placeholder: "项目名称"
      },
      page: 1,
      total: 0,
      pagesize: 10,

      dialogStatus: "",
      textMap: {
        update: "编辑项目",
        create: "新增项目",
        updatePic: "编辑项目图片"
      },
      dialogFormVisible: false,
      dialogPicListVisible: false,
      Form: {
        name: "",
        customerId: null,
        createdAt: new Date(),
        customerAddr: "",
        customerContact: "",
        description: "",
        planEndDate: new Date(),
        planStartDate: new Date(),
        state: null,
        picList: []
      },
      FormRules: {
        name: [{ required: true, message: "请填写项目名称", trigger: "blur" }],
        customerId: [
          { required: true, message: "请选择服务客户", trigger: "change" }
        ],
        createdAt: [
          {
            type: "date",
            required: true,
            message: "请填写创建时间",
            trigger: "change"
          }
        ],
        customerAddr: [
          { required: true, message: "请填写项目服务地址", trigger: "blur" }
        ],
        customerContact: [
          { required: true, trigger: "blur", validator: validPhone }
        ],
        planStartDate: [
          {
            required: true,
            message: "请填写项目计划开始时间",
            trigger: "change"
          }
        ],
        planEndDate: [
          {
            required: true,
            message: "请填写项目计划完成时限",
            trigger: "change"
          }
        ],
        picList: [
          { required: true, message: "请上传项目图片", trigger: "change" }
        ]
      },
      StartOptions: {
        disabledDate: time => {
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      EndOptions: {
        disabledDate: time => {
          return time.getTime() < this.Form.planStartDate;
        }
      }
    };
  },

  created() {
    this.getList();
    this.getCustomerCode();
  },
  watch: {
    Form: {
      handler(newval, oldval) {
        this.Form.picList = newval.picList;
      },
      deep: true,
      immediate: true
    }
  },

  methods: {
    checkPermission,
    //获取工程师列表
    getEngineer() {},

    // 翻页
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },
    // 获取客户
    getCustomerCode() {
      getCustomerAll().then(response => {
        this.customersOptions = response.data.map(item => {
          return { customerId: item.id, customerName: item.customerName };
        });
      });
    },

    //图片上传检查
    handleChange(file, fileList) {
      const isImage =
        file.raw.type == "image/png" ||
        file.raw.type == "image/jpg" ||
        file.raw.type == "image/jpeg";
      if (!isImage) {
        this.$message.error("上传图片只能是JPG或者png格式!");
      }
      if (isImage) {
        this.Form.picList = fileList;
      } else {
        fileList.pop();
      }
      return isImage
    },

    // 上传成功后
    handleAvatarSuccess(response, file, fileList) {
      this.$message({
        message: "图片上传成功",
        type: "success"
      });
      this.dialogPicListVisible = false;
      this.getList();
    },

    // 删除图片
    handleRemove(file, fileList) {
      if (file.hasOwnProperty("fid")) {
        deletePic({ fid: file.fid });
      }
    },

    beforeRemove(file, fileList) {
      if (file.hasOwnProperty("originname")) {
        if (fileList.length > 1) {
          return this.$confirm(`确定移除 ${file.originname}？`);
        } else {
          this.$message({
            message: "项目需至少保留一张图片",
            type: "warning"
          });
          return false;
        }
      }
    },

    //获取列表
    getList() {
      this.listLoading = true;
      let data = {
        name: this.filters.name,
        page: this.page,
        size: this.pagesize,
        state: parseInt(this.state)
      };
      getTaskList(data).then(response => {
        this.taskList = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    // 翻页
    handleCurrentChange(val) {
      this.page = val;
      this.getList();
    },

    //编辑子项目进度
    handleProgress(index, row) {
      this.$router.push({
        path: "/task/project/progress/" + row.pid
      });
    },

    //进入子项目列表
    handleClick(index, row) {
      this.$router.push({
        path: "/task/project/" + row.id
      });
    },
    //子项目跟踪
    handleProjectTrack(index, row) {
      this.$router.push({
        path: "/task/project/track/" + row.pid
      });
    },
    //进入主项目跟踪
    handleTaskTrack(index, row) {
      this.$router.push({
        path: "/task/track/" + row.id
      });
    },

    //重置form
    resetForm() {
      this.Form = {
        name: "",
        createdAt: new Date(),
        customerAddr: "",
        customerContact: "",
        description: "",
        planEndDate: new Date(),
        planStartDate: new Date(),
        state: null,
        picList: []
      };
    },
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },

    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.Form.state = 1;
          let tempData = Object.assign({}, this.Form);
          createTask(tempData).then(res => {
            let taskId = res.data.insertId;
            this.Data = { taskId: taskId };
            this.$nextTick(() => {
              this.$refs.taskPic.UploadSubmit();
            });
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: "成功",
              message: "新增项目成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },

    //显示编辑界面
    handleUpdate(index, row) {
      this.Form = Object.assign(this.Form, row);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },
    //编辑
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.Form);
          updateTask(tempData).then(() => {
            this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },

    //显示图片编辑界面
    handleUpdatePic(index, row) {
      this.picList = [];
      this.dialogStatus = "updatePic";
      this.Data = { taskId: row.id };
      getTaskData({ taskId: row.id }).then(response => {
        this.picList = response.data.picList;
        this.dialogPicListVisible = true;
      });
    }
  }
};
</script>
